<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>Zookeper | Hexo</title><meta name="author" content="John Doe"><meta name="copyright" content="John Doe"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Zookeper0. 是什么 Zookeeper是一个高性能、分布式的开源的协作服务；  提供一系列简单的功能，分布式应用可以在此基础上实现例如数据发布&#x2F;订阅、负载均衡、命名服务、分布式协调&#x2F;通知、集群管理、Leader选举、分布式锁和分布式队列等；   0.0 特性 高可用性：能避免单点故障，最多可在n-1个节点故障状态下工作； 顺序一致性：来自客户端的更新将按照发送的顺序被">
<meta property="og:type" content="article">
<meta property="og:title" content="Zookeper">
<meta property="og:url" content="https://z-w-t.gitee.io/2023/10/25/Zookeper/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="Zookeper0. 是什么 Zookeeper是一个高性能、分布式的开源的协作服务；  提供一系列简单的功能，分布式应用可以在此基础上实现例如数据发布&#x2F;订阅、负载均衡、命名服务、分布式协调&#x2F;通知、集群管理、Leader选举、分布式锁和分布式队列等；   0.0 特性 高可用性：能避免单点故障，最多可在n-1个节点故障状态下工作； 顺序一致性：来自客户端的更新将按照发送的顺序被">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png">
<meta property="article:published_time" content="2023-10-25T03:19:39.229Z">
<meta property="article:modified_time" content="2023-10-25T12:15:11.456Z">
<meta property="article:author" content="John Doe">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png"><link rel="shortcut icon" href="/zwt-life/img/favicon.png"><link rel="canonical" href="https://z-w-t.gitee.io/2023/10/25/Zookeper/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/zwt-life/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/zwt-life/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: 'Copy Successful',
    error: 'Copy Error',
    noSupport: 'Browser Not Supported'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: 'Just now',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: 'Load More'
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Zookeper',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-10-25 20:15:11'
}</script><script>(win=>{
      win.saveToLocal = {
        set: (key, value, ttl) => {
          if (ttl === 0) return
          const now = Date.now()
          const expiry = now + ttl * 86400000
          const item = {
            value,
            expiry
          }
          localStorage.setItem(key, JSON.stringify(item))
        },
      
        get: key => {
          const itemStr = localStorage.getItem(key)
      
          if (!itemStr) {
            return undefined
          }
          const item = JSON.parse(itemStr)
          const now = Date.now()
      
          if (now > item.expiry) {
            localStorage.removeItem(key)
            return undefined
          }
          return item.value
        }
      }
    
      win.getScript = (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        script.onerror = reject
        script.onload = script.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          script.onload = script.onreadystatechange = null
          resolve()
        }

        Object.keys(attr).forEach(key => {
          script.setAttribute(key, attr[key])
        })

        document.head.appendChild(script)
      })
    
      win.getCSS = (url, id = false) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onerror = reject
        link.onload = link.onreadystatechange = function() {
          const loadState = this.readyState
          if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
          link.onload = link.onreadystatechange = null
          resolve()
        }
        document.head.appendChild(link)
      })
    
      win.activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
        if (t === 'dark') activateDarkMode()
        else if (t === 'light') activateLightMode()
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
      const detectApple = () => {
        if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
          document.documentElement.classList.add('apple')
        }
      }
      detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/zwt-life/archives/"><div class="headline">Articles</div><div class="length-num">6</div></a><a href="/zwt-life/tags/"><div class="headline">Tags</div><div class="length-num">0</div></a><a href="/zwt-life/categories/"><div class="headline">Categories</div><div class="length-num">0</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/zwt-life/"><i class="fa-fw fas fa-home"></i><span> 首頁</span></a></div><div class="menus_item"><a class="site-page" href="/zwt-life/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/zwt-life/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/zwt-life/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/zwt-life/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/zwt-life/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/zwt-life/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/zwt-life/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/zwt-life/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a href="/zwt-life/" title="Hexo"><span class="site-name">Hexo</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/zwt-life/"><i class="fa-fw fas fa-home"></i><span> 首頁</span></a></div><div class="menus_item"><a class="site-page" href="/zwt-life/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/zwt-life/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/zwt-life/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-heartbeat"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/zwt-life/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/zwt-life/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/zwt-life/movies/"><i class="fa-fw fas fa-video"></i><span> 电影</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/zwt-life/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/zwt-life/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Zookeper</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2023-10-25T03:19:39.229Z" title="Created 2023-10-25 11:19:39">2023-10-25</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2023-10-25T12:15:11.456Z" title="Updated 2023-10-25 20:15:11">2023-10-25</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Zookeper"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post Views:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Zookeper"><a href="#Zookeper" class="headerlink" title="Zookeper"></a>Zookeper</h1><h2 id="0-是什么"><a href="#0-是什么" class="headerlink" title="0. 是什么"></a>0. 是什么</h2><ul>
<li><p>Zookeeper是一个高性能、分布式的开源的协作服务；</p>
</li>
<li><p>提供一系列简单的功能，分布式应用可以在此基础上实现例如数据发布&#x2F;订阅、负载均衡、命名服务、分布式协调&#x2F;通知、集群管理、Leader选举、分布式锁和分布式队列等；</p>
</li>
</ul>
<h3 id="0-0-特性"><a href="#0-0-特性" class="headerlink" title="0.0 特性"></a>0.0 特性</h3><ul>
<li>高可用性：能避免单点故障，最多可在n-1个节点故障状态下工作；</li>
<li>顺序一致性：来自客户端的更新将按照发送的顺序被写入到zookeeper中；</li>
<li>原子性：更新操作要么成功要么失败，没有中间状态；</li>
<li>可靠性：事务一旦执行成功，状态永久保留</li>
<li>单一系统映像：无论客户端连到哪一个 ZooKeeper 服务器上，客户端看到的服务端数据视图都不会是较旧的数据视图；</li>
<li>实时性：zookeeper保证客户端将在一个时间间隔范围内获得服务器的更新信息，或者服务器失效的信息。但由于网络延时等原因，zookeeper不能保证两个客户端能同时得到刚更新的数据，如果需要最新数据，最好在读数据之前调用sync()接口。</li>
</ul>
<h3 id="0-1-总体架构"><a href="#0-1-总体架构" class="headerlink" title="0.1 总体架构"></a>0.1 总体架构</h3><p>​	Zookeeper服务可单机也可集群（2n+1个服务允许n个失效）部署。 <img src="/zwt-life/./Zookeper.assets/ee39fa49dafb4f8eb18ab5af691491ea~tplv-k3u1fbpfcp-zoom-in-crop-mark:1512:0:0:0.awebp" alt="img"></p>
<ul>
<li>每个Server在内存中存储一份数据，并维护当前服务状态，服务与服务保持通信；</li>
<li>Zookeeper启动时，将从实例中选举一个Leader（Paxos协议）；</li>
<li>Leader提供写服务和读服务，Follower提供读服务；</li>
<li>集群间通过Zab（Zookeeper Atomic Broadcast）协议保证数据一致性；</li>
<li>一个更新操作成功，当且仅当大多数Server在内存中成功修改数据；</li>
</ul>
<h3 id="0-2-角色"><a href="#0-2-角色" class="headerlink" title="0.2 角色"></a>0.2 角色</h3><p>​	Zookeeper引入了Leader、Follower 和 Observer 三种角色。Leader既提供写服务又能提供读服务。除了Leader外，Follower和Observer只能提供读服务。</p>
<p><img src="/zwt-life/./Zookeper.assets/41ece1f9a5c04992a800cb00eb12f527~tplv-k3u1fbpfcp-zoom-in-crop-mark:1512:0:0:0.awebp" alt="img"></p>
<h3 id="0-3数据模型"><a href="#0-3数据模型" class="headerlink" title="0.3数据模型"></a>0.3数据模型</h3><p><img src="/zwt-life/./Zookeper.assets/26aaceac639743c9a8581786eaf11051~tplv-k3u1fbpfcp-zoom-in-crop-mark:1512:0:0:0.awebp" alt="img"></p>
<p>​	Zookeeper采用多层次化的目录结构，类似文件系统的数据结构。Zookeeper结构由节点组成，数据存储也基于节点，这种节点叫做ZNode。ZNode数据保存在内存中，意味着Zookeeper可以实现高吞吐量和低延迟。</p>
<p><img src="/zwt-life/./Zookeper.assets/2fef15c652244abb8cf290c98f1192c4~tplv-k3u1fbpfcp-zoom-in-crop-mark:1512:0:0:0.awebp" alt="img"></p>
<ul>
<li>Data：ZNode存储的数据信息。</li>
<li>ACL：记录ZNode的访问权限，即哪些人或哪些IP可以访问本节点。</li>
<li>Stat：包含ZNode的各种元数据，比如事务ID、版本号、时间戳、大小等等。</li>
<li>Child：当前节点的子节点引用，类似于二叉树的左孩子右孩子。</li>
</ul>
<h3 id="0-4-四种节点"><a href="#0-4-四种节点" class="headerlink" title="0.4 四种节点"></a>0.4 四种节点</h3><p>  临时节点（EPHEMERAL） ：session链接断开就没了；不能创建子节点；不能同名</p>
<p>  临时顺序节点（EPHEMERAL_SEQUENTIAL） ：session链接断开就没了；不能创建子节点；同名节点会在后面添加上序号（分布式锁使用的好处）</p>
<p>  持久节点（PERSISTENT）：session断联、服务端重启还在；可以创建子节点，子节点可以临时也可以持久；不能同名</p>
<p>  持久顺序节点（PERSISTENT_SEQUENTIAL）：session断联、服务端重启还在；可以创建子节点，子节点可以临时也可以持久；同名节点会在后面添加上序号</p>
<h2 id="1-为什么要使用"><a href="#1-为什么要使用" class="headerlink" title="1. 为什么要使用"></a>1. 为什么要使用</h2><p>ZooKeeper 是：</p>
<ol>
<li>分布式协调服务</li>
<li>高效、可靠</li>
<li>方便应用程序，聚焦<code>业务逻辑开发</code>，而不需要过多关注<code>分布式进程间协作细节</code></li>
</ol>
<p>ZooKeeper 不直接暴露<code>原语</code>，而是，暴露一部分<code>调用方法</code>组成的 API，类似文件系统的 API，支持应用程序实现自己的<code>原语</code></p>
<h3 id="ZooKeeper-设计目标"><a href="#ZooKeeper-设计目标" class="headerlink" title="ZooKeeper 设计目标"></a>ZooKeeper 设计目标</h3><p>ZooKeeper 致力于提供<code>高性能</code>、<code>高可用</code>、<code>顺序一致性</code>的分布式协调服务，保证数据<code>最终一致性</code>。</p>
<h3 id="目标一：高性能（简单的数据模型）"><a href="#目标一：高性能（简单的数据模型）" class="headerlink" title="[目标一：高性能（简单的数据模型）]"></a>[<strong>目标一：高性能（简单的数据模型）</strong>]</h3><ol>
<li>采用<code>树形结构</code>组织数据节点；</li>
<li>全量数据节点，都存储在内存中；</li>
<li>Follower 和 Observer 直接处理非事务请求；</li>
</ol>
<h3 id="目标二：高可用（构建集群）"><a href="#目标二：高可用（构建集群）" class="headerlink" title="[目标二：高可用（构建集群）]"></a>[<strong>目标二：高可用（构建集群）</strong>]</h3><ol>
<li>半数以上机器存活，服务就能正常运行</li>
<li>自动进行 Leader 选举</li>
</ol>
<h3 id="目标三：顺序一致性（事务操作的顺序）"><a href="#目标三：顺序一致性（事务操作的顺序）" class="headerlink" title="[目标三：顺序一致性（事务操作的顺序）]"></a>[<strong>目标三：顺序一致性（事务操作的顺序）</strong>]</h3><ol>
<li>每个事务请求，都会转发给 Leader 处理</li>
<li>每个事务，会分配全局唯一的递增id（zxid，64位：epoch + 自增 id）</li>
</ol>
<h3 id="目标四：最终一致性"><a href="#目标四：最终一致性" class="headerlink" title="[目标四：最终一致性]"></a>[<strong>目标四：最终一致性</strong>]</h3><ol>
<li>通过提议投票方式，保证事务提交的可靠性</li>
<li>提议投票方式，只能保证 Client 收到事务提交成功后，半数以上节点能够看到最新数据</li>
</ol>
<h2 id="2-使用场景"><a href="#2-使用场景" class="headerlink" title="2. 使用场景"></a>2. 使用场景</h2><h3 id="2-1-命名服务（Name-Service）"><a href="#2-1-命名服务（Name-Service）" class="headerlink" title="2.1 命名服务（Name Service）"></a>2.1 命名服务（Name Service）</h3><ul>
<li>分布式应用中，通常需要有一套完整的命名规则，既能够产生唯一的名称又便于人识别和记住，通常情况下用树形的名称结构是一个理想的选择，树形的名称结构是一个层次的目录结构，即对人友好又不重复。</li>
<li>Name Service是Zookeeper内置的功能，你只要调用Zookeeper的API就能实现。如调用create接口就可以很容易创建一个目录节点。</li>
</ul>
<h3 id="2-2-配置中心"><a href="#2-2-配置中心" class="headerlink" title="2.2 配置中心"></a>2.2 配置中心</h3><ul>
<li><p>创建存储配置信息的节点</p>
</li>
<li><p>客户端设置监听该节点的watcher</p>
</li>
<li><p>配置信息变更，客户端被通知</p>
</li>
<li><p>客户端更新配置信息</p>
</li>
</ul>
<h3 id="2-3-集群管理"><a href="#2-3-集群管理" class="headerlink" title="2.3 集群管理"></a>2.3 集群管理</h3><ul>
<li><p>集群中所有机器去&#x2F;GroupMembers目录下创建自增编号的临时节点，并监听&#x2F;GroupMembers目录；</p>
</li>
<li><p>编号最小的成为Leader；</p>
</li>
<li><p>当集群中的一台机器宕机，该节点从&#x2F;GroupMembers中移除，同时其他活动节点接收到监听消息，同时这时编号最小的节点成为Leader；</p>
</li>
</ul>
<h3 id="2-4-分布式锁"><a href="#2-4-分布式锁" class="headerlink" title="2.4 分布式锁"></a>2.4 分布式锁</h3><p>​	节点 &#x2F;Locks 已经预先存在，所有客户端在它下面创建临时顺序编号目录节点，和选master一样，编号最小的获得锁，用完删除，编号大的监听前一个节点是否存在，不存在就判断是否获得锁。否则等待</p>
<h2 id="3-如何使用"><a href="#3-如何使用" class="headerlink" title="3. 如何使用"></a>3. 如何使用</h2><h3 id="3-1-java-实现"><a href="#3-1-java-实现" class="headerlink" title="3.1 java 实现"></a>3.1 java 实现</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span>       </span><br><span class="line">  <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.101tec<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>zkclient<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">version</span>&gt;</span>0.11<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="建立关闭连接"><a href="#建立关闭连接" class="headerlink" title="建立关闭连接"></a>建立关闭连接</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">    <span class="comment">//建立连接</span></span><br><span class="line">    <span class="comment">//zkServers: Zookeeper服务器IP地址和端口号，如果是集群情况下用逗号分割多个Zookeeper服务器地址</span></span><br><span class="line">    <span class="comment">//sessionTimeout: 会话超时时间</span></span><br><span class="line">    <span class="comment">//connectionTimeout: 连接超时时间</span></span><br><span class="line">    <span class="type">ZkClient</span> <span class="variable">zkClient</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ZkClient</span>(<span class="string">&quot;127.0.0.1:2181&quot;</span>, <span class="number">60000</span>, <span class="number">5000</span>);</span><br><span class="line">zkClient.close();</span><br></pre></td></tr></table></figure>

<h4 id="创建节点"><a href="#创建节点" class="headerlink" title="创建节点"></a>创建节点</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//创建数据</span></span><br><span class="line">      <span class="type">Student</span> <span class="variable">student</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Student</span>();</span><br><span class="line">      student.setName(<span class="string">&quot;张三&quot;</span>);</span><br><span class="line">      student.setAge(<span class="number">18</span>);</span><br><span class="line">      student.setPhone(<span class="string">&quot;1585454xxxx&quot;</span>);</span><br><span class="line">      <span class="comment">//创建持久节点</span></span><br><span class="line">      zkClient.createPersistent(<span class="string">&quot;/p_node&quot;</span>, student);</span><br><span class="line">      zkClient.createPersistent(<span class="string">&quot;/p_node/dd&quot;</span>, student);</span><br><span class="line">      <span class="comment">//创建临时节点</span></span><br><span class="line">      zkClient.createEphemeral(<span class="string">&quot;/r_node&quot;</span>, student);</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="创建顺序节点"><a href="#创建顺序节点" class="headerlink" title="创建顺序节点"></a>创建顺序节点</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">    <span class="comment">//创建顺序节点之前先创建持久节点</span></span><br><span class="line">    <span class="comment">// 创建持久节点</span></span><br><span class="line">    zkClient.createPersistent(<span class="string">&quot;/ps&quot;</span>, <span class="literal">true</span>);</span><br><span class="line">    <span class="comment">// 添加持久有序节点</span></span><br><span class="line">    <span class="type">String</span> <span class="variable">sequentialNode</span> <span class="operator">=</span> zkClient.createPersistentSequential(<span class="string">&quot;/ps/node-&quot;</span>, <span class="string">&quot;datsfdnvfndsa&quot;</span>);</span><br><span class="line">    System.out.println(<span class="string">&quot;Created sequential node: &quot;</span> + sequentialNode);</span><br><span class="line"><span class="comment">//输出 Created sequential node: /ps/node-0000000004</span></span><br><span class="line">    <span class="comment">// 获取有序节点数据</span></span><br><span class="line">    <span class="type">String</span> <span class="variable">data</span> <span class="operator">=</span> zkClient.readData(sequentialNode);</span><br><span class="line">    System.out.println(<span class="string">&quot;Node data: &quot;</span> + <span class="keyword">new</span> <span class="title class_">String</span>(data));</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">//创建临时顺序节点</span></span><br><span class="line"><span class="comment">    zkClient.createEphemeralSequential(&quot;/ps/node-&quot;, &quot;datsfdnvfndsa&quot;);</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<h4 id="更新节点"><a href="#更新节点" class="headerlink" title="更新节点"></a>更新节点</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//更新节点数据</span></span><br><span class="line">zkClient.writeData(<span class="string">&quot;/p_node&quot;</span>, <span class="string">&quot;myData1&quot;</span>);</span><br></pre></td></tr></table></figure>

<h4 id="访问节点"><a href="#访问节点" class="headerlink" title="访问节点"></a>访问节点</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//访问节点</span></span><br><span class="line">    <span class="type">Stat</span> <span class="variable">stat</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Stat</span>();</span><br><span class="line">    <span class="type">Object</span> <span class="variable">student1</span> <span class="operator">=</span> zkClient.readData(<span class="string">&quot;/p_node&quot;</span>, stat);</span><br><span class="line">    System.out.println(<span class="string">&quot;节点状态信息：&quot;</span> + JSON.toJSONString(student1));</span><br><span class="line">    System.out.println(<span class="string">&quot;节点数据：&quot;</span> + JSON.toJSONString(stat));</span><br><span class="line"><span class="comment">//访问节点</span></span><br><span class="line">    <span class="type">String</span> <span class="variable">data</span> <span class="operator">=</span> zkClient.readData(sequentialNode);</span><br><span class="line"><span class="comment">//访问子节点</span></span><br><span class="line">    List&lt;String&gt; childList = zkClient.getChildren(<span class="string">&quot;/p_node&quot;</span>);</span><br><span class="line">    <span class="keyword">for</span> (String s1 : childList) &#123;</span><br><span class="line">        <span class="type">Object</span> <span class="variable">student1</span> <span class="operator">=</span> zkClient.readData(s1);</span><br><span class="line">        System.out.println(s1);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h4 id="添加监听"><a href="#添加监听" class="headerlink" title="添加监听"></a>添加监听</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">jianting</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">ZkClient</span> <span class="variable">zkClient</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ZkClient</span>(<span class="string">&quot;127.0.0.1:2181&quot;</span>, <span class="number">60000</span>, <span class="number">5000</span>);</span><br><span class="line">        zkClient.subscribeChildChanges(<span class="string">&quot;/p_node&quot;</span>, <span class="keyword">new</span> <span class="title class_">IZkChildListener</span>() &#123;</span><br><span class="line">            <span class="comment">//子节点改变时调用</span></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">handleChildChange</span><span class="params">(String parentPath, List&lt;String&gt; currentChilds)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">                System.out.println(parentPath + <span class="string">&quot;子节点发生改变&quot;</span>);</span><br><span class="line">                System.out.println(<span class="string">&quot;当前子节点列表：&quot;</span> + currentChilds);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//阻塞客户端，便于测试</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            System.in.read();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">RuntimeException</span>(e);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//输出</span></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">/p_node子节点发生改变</span></span><br><span class="line"><span class="comment">当前子节点列表：null</span></span><br><span class="line"><span class="comment">/p_node子节点发生改变</span></span><br><span class="line"><span class="comment">当前子节点列表：[asf]</span></span><br><span class="line"><span class="comment">/p_node子节点发生改变</span></span><br><span class="line"><span class="comment">当前子节点列表：[dd, asf]</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<h4 id="删除节点"><a href="#删除节点" class="headerlink" title="删除节点"></a>删除节点</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//删除节点，不能删除带有子节点的节点</span></span><br><span class="line">zkClient.delete(<span class="string">&quot;/p_node&quot;</span>);</span><br><span class="line"><span class="comment">//删除节点，递归删除所有子孙节点</span></span><br><span class="line">zkClient.deleteRecursive(<span class="string">&quot;/ps_node&quot;</span>);</span><br></pre></td></tr></table></figure>



<h2 id="4-原理"><a href="#4-原理" class="headerlink" title="4. 原理"></a>4. 原理</h2><h3 id="4-1-Session-会话"><a href="#4-1-Session-会话" class="headerlink" title="4.1 Session 会话"></a>4.1 Session 会话</h3><ul>
<li>Session 指的是 ZooKeeper  服务器与客户端会话。</li>
<li><strong>在ZooKeeper中，一个客户端连接是指客户端和服务器之间的一个 TCP 长连接。</strong></li>
<li><strong>通过这个连接，客户端能够通过心跳检测与服务器保持有效的会话，也能够向Zookeeper服务器发送请求并接受响应，同时还能够通过该连接接收来自服务器的Watch事件通知。</strong> Session的sessionTimeout值用来设置一个客户端会话的超时时间。当由于服务器压力太大、网络故障或是客户端主动断开连接等各种原因导致客户端连接断开时，<strong>只要在sessionTimeout规定的时间内能够重新连接上集群中任意一台服务器，那么之前创建的会话仍然有效。</strong></li>
<li><strong>在为客户端创建会话之前，服务端首先会为每个客户端都分配一个sessionID。</strong> 由于 sessionID 是 Zookeeper 会话的一个重要标识，许多与会话相关的运行机制都是基于这个 sessionID 的，因此，<strong>无论是哪台服务器为客户端分配的 sessionID，都务必保证全局唯一。</strong></li>
</ul>
<h3 id="4-2-ZNode-节点"><a href="#4-2-ZNode-节点" class="headerlink" title="4.2 ZNode 节点"></a>4.2 ZNode 节点</h3><ul>
<li>Zookeeper将所有数据存储在内存中，数据模型是一棵树（ZNode Tree)，由斜杠（&#x2F;）的进行分割的路径，就是一个ZNode，例如&#x2F;foo&#x2F;path1。每个ZNode上都会保存自己的数据内容，同时还会保存一系列属性信息。</li>
<li><strong>ZNode可以分为持久节点和临时节点两类。</strong> 所谓持久节点是指一旦这个ZNode被创建了，除非主动进行ZNode的移除操作，否则这个ZNode将一直保存在Zookeeper上。而临时节点就不一样了，它的生命周期和客户端会话绑定，一旦客户端会话失效，那么这个客户端创建的所有临时节点都会被移除。</li>
<li><strong>ZooKeeper还允许用户为每个节点添加一个特殊的属性：SEQUENTIAL。一旦节点被标记上这个属性，那么在这个节点被创建的时候，Zookeeper会自动在其节点名后面追加上一个整型数字，这个整型数字是一个由父节点维护的自增数字。</strong></li>
<li><strong>ZNode大小限制为1M。</strong> 通常存储配置信息，元数据信息，不建议存储较大的数据。</li>
</ul>
<p>ZNode节点信息：</p>
<ul>
<li>cZxid：这是导致创建znode更改的事务ID。</li>
<li>mZxid：这是最后修改znode更改的事务ID。</li>
<li>pZxid：这是用于添加或删除子节点的znode更改的事务ID。</li>
<li>ctime：表示从1970-01-01T00:00:00Z开始以毫秒为单位的znode创建时间。</li>
<li>mtime：表示从1970-01-01T00:00:00Z开始以毫秒为单位的znode最近修改时间。</li>
<li>dataVersion：表示对该znode的数据所做的更改次数。</li>
<li>cversion：这表示对此znode的子节点进行的更改次数。</li>
<li>aclVersion：表示对此znode的ACL进行更改的次数。</li>
<li>ephemeralOwner：如果znode是ephemeral类型节点，则这是znode所有者的 session ID。 如果znode不是ephemeral节点，则该字段设置为零。</li>
<li>dataLength：这是znode数据字段的长度。</li>
<li>numChildren：这表示znode的子节点的数量。</li>
</ul>
<h3 id="4-3-Watcher-监听器"><a href="#4-3-Watcher-监听器" class="headerlink" title="4.3 Watcher 监听器"></a>4.3 Watcher 监听器</h3><p>Watcher（事件监听器），Zookeeper允许用户在指定节点上注册一些Watcher，并且在调用create，delete，setData方法的时候，将会触发ZNode上注册的对应事件的监听器，向客户端发送异步通知。</p>
<p><img src="/zwt-life/./Zookeper.assets/708f878862a6451eb67853383e95bfd4~tplv-k3u1fbpfcp-zoom-in-crop-mark:1512:0:0:0.awebp" alt="img"></p>
<p><img src="/zwt-life/./Zookeper.assets/4e929536e17f42c58cc6eef68f87aefc~tplv-k3u1fbpfcp-zoom-in-crop-mark:1512:0:0:0.awebp" alt="img"></p>
<h3 id="4-4-ACL-权限控制"><a href="#4-4-ACL-权限控制" class="headerlink" title="4.4 ACL 权限控制"></a>4.4 ACL 权限控制</h3><p>Zookeeper采用ACL（AccessControlLists）策略来进行权限控制，类似于 UNIX 文件系统的权限控制。Zookeeper 定义了如下5种权限。</p>
<ul>
<li><strong>CREATE（c）</strong>    可以创建子节点</li>
<li><strong>DELETE（d）</strong>    可以删除子节点（仅下一级节点）</li>
<li><strong>READ（r）</strong>      可以读取节点数据及显示子节点列表</li>
<li><strong>WRITE（w）</strong>     可以设置节点数据</li>
<li><strong>ADMIN（a）</strong>     可以设置节点访问控制列表权限</li>
</ul>
<p>权限模式：</p>
<ul>
<li><strong>world：</strong> 默认节点权限, 固定值anyone为ACL ID，代表所有人。</li>
<li><strong>auth：</strong> 用户密码认证，需要使用addauth添加用户信息，添加多个用户，则权限相同。</li>
<li><strong>digest：</strong> 用户密码认证，使用username:password设置ACL，password需要密文base64(sha1(password))，设置时无需addauth添加用户信息。</li>
<li><strong>ip：</strong> 使用客户端的主机IP作为ACL ID。</li>
</ul>
<p>通过 [scheme:id:permissions] 格式设置权限，如下：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">bash</span><br><span class="line">复制代码setAcl /test/child world:anyone:crwa</span><br></pre></td></tr></table></figure>

<h3 id="4-5-ZAB-原子广播"><a href="#4-5-ZAB-原子广播" class="headerlink" title="4.5 ZAB 原子广播"></a>4.5 ZAB 原子广播</h3><p>ZAB（ZooKeeper Atomic Broadcast 原子广播） 协议，有效的解决了Zookeeper集群崩溃恢复，以及主从同步数据的问题。</p>
<p>ZAB协议定义了三种节点状态：</p>
<ul>
<li>Looking：选举状态。</li>
<li>Following：Follower节点（从节点）所处的状态。</li>
<li>Leading：Leader节点（主节点）所处状态。</li>
</ul>
<p>最大ZXID概念：最大ZXID也就是节点本地的最新事务编号。</p>
<h4 id="4-5-1-奔溃恢复"><a href="#4-5-1-奔溃恢复" class="headerlink" title="4.5.1 奔溃恢复"></a>4.5.1 奔溃恢复</h4><p>假如Zookeeper当前的主节点挂掉了，集群会进行崩溃恢复。ZAB的崩溃恢复分成三个阶段：</p>
<ol>
<li>Leader election（选举阶段）</li>
</ol>
<p><img src="/zwt-life/./Zookeper.assets/93fc1545be6a47cda3a30a05136b2778~tplv-k3u1fbpfcp-zoom-in-crop-mark:1512:0:0:0.awebp" alt="img"> <img src="/zwt-life/./Zookeper.assets/b32330ff18f74fd1a0b3928c643aaab6~tplv-k3u1fbpfcp-zoom-in-crop-mark:1512:0:0:0.awebp" alt="img"> <img src="/zwt-life/./Zookeper.assets/115c3e0af9b742e4abbdaf549dfed39b~tplv-k3u1fbpfcp-zoom-in-crop-mark:1512:0:0:0.awebp" alt="img"></p>
<ol start="2">
<li>Discovery（发现阶段） 发现阶段，用于在从节点中发现最新的ZXID和事务日志。或许有人会问：既然Leader被选为主节点，已经是集群里数据最新的了，为什么还要从节点中寻找最新事务呢？</li>
</ol>
<p>这是为了防止某些意外情况，比如因网络原因在上一阶段产生多个Leader的情况，脑裂场景。</p>
<p>所以这一阶段，Leader集思广益，接收所有Follower发来的最新epoch值。Leader从中选出最大的epoch，基于此值加1，生成新的epoch分发给各个Follower。</p>
<p>各个Follower收到全新的epoch后，返回ACK给Leader，带上各自最大的ZXID和历史事务日志。Leader选出最大的ZXID，并更新自身历史日志。</p>
<p>3.Synchronization（同步阶段）</p>
<p>把Leader刚才收集得到的最新历史事务日志，同步给集群中所有的Follower。只有当半数Follower同步成功，这个准Leader才能成为正式的Leader。自此，故障恢复正式完成。</p>
<h4 id="4-5-2-广播过程"><a href="#4-5-2-广播过程" class="headerlink" title="4.5.2 广播过程"></a>4.5.2 广播过程</h4><p>Zookeeper常规情况下更新数据的时候，由Leader广播到所有的Follower。其过程如下：</p>
<ol>
<li>客户端发出写入数据请求给任意Follower。</li>
<li>Follower把写入数据请求转发给Leader。</li>
<li>Leader采用二阶段提交方式，先发送Propose广播给Follower。</li>
<li>Follower接到Propose消息，写入日志成功后，返回ACK消息给Leader。</li>
<li>Leader接到半数以上ACK消息，返回成功给客户端，并且广播Commit请求给Follower。</li>
</ol>
<p><img src="/zwt-life/./Zookeper.assets/13a9d8e1386b48bf86d973f522e1520e~tplv-k3u1fbpfcp-zoom-in-crop-mark:1512:0:0:0.awebp" alt="img"></p>
<h2 id="番外"><a href="#番外" class="headerlink" title="番外"></a>番外</h2><h3 id="zxid，epoch"><a href="#zxid，epoch" class="headerlink" title="zxid，epoch"></a>zxid，epoch</h3><p>zxid 就是我们<a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s?__biz=MzA5MzYyNzQ0MQ==&mid=2247499173&idx=1&sn=8d09888533c4a75d2915720c1242ee13&chksm=905848fba72fc1ed38659069914313885499d89bd3259fcc95ef0604c8bbc1851f2cc31e85f7&token=638365590&lang=zh_CN#rd">之前</a>提到的事务编号，是一个 8 字节的整型数字，但是 ZK 设计的时候把这一个数字拆成了两部分使用，一鱼两吃！</p>
<p>8 个字节的整数一共有 64 位长度，前 32 位用来记录 epoch，后 32 位就是用来计数。你可能要问了？ epoch？是啥？</p>
<p>zxid 初始化是 0，也就是这样</p>
<figure class="highlight basic"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="symbol">00000000000000000000000000000000 </span><span class="number">00000000000000000000000000000000</span></span><br></pre></td></tr></table></figure>

<p>每一次写请求都会增加后 32 位，假设现在进行了 10 次写请求（无论该请求有没有真的修改到数据），zxid 就会变成这样</p>
<figure class="highlight basic"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="symbol">00000000000000000000000000000000 </span><span class="number">00000000000000000000000000001010</span></span><br></pre></td></tr></table></figure>

<p>当进行一次选举的时候，前 32 位就会增加 1，并且清零后 32 位</p>
<figure class="highlight basic"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="symbol">00000000000000000000000000000001 </span><span class="number">00000000000000000000000000000000</span></span><br></pre></td></tr></table></figure>

<p>除了选举以外，当后 32 位彻底用完（变成全 1，也就是 ZK 正常执行了 2^32 - 1 次写请求都没进行过一次选举，牛逼！）也会让前 32 位增加 1，相当于进位</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 进位前</span></span><br><span class="line">00000000000000000000000000000000 11111111111111111111111111111111</span><br><span class="line"><span class="comment"># 进位后</span></span><br><span class="line">00000000000000000000000000000001 00000000000000000000000000000000</span><br></pre></td></tr></table></figure>

<p>到这里我就可以回答大家前面的问题了，epoch 就是 zxid 前 32 位的这个数字，epoch 本身的翻译是“纪元，时代”的意思，意味着更新换代，而 zxid 的后 32 位数字仅仅是写请求的计数罢了</p>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><p><a target="_blank" rel="noopener" href="https://cloud.tencent.com/developer/article/1770764">https://cloud.tencent.com/developer/article/1770764</a></p>
<p><a target="_blank" rel="noopener" href="https://juejin.cn/post/6911981919974457358">https://juejin.cn/post/6911981919974457358</a></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>Author: </span><span class="post-copyright-info"><a href="https://z-w-t.gitee.io">John Doe</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>Link: </span><span class="post-copyright-info"><a href="https://z-w-t.gitee.io/2023/10/25/Zookeper/">https://z-w-t.gitee.io/2023/10/25/Zookeper/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/zwt-life/2023/10/25/todo/" title="todo"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">Previous</div><div class="prev_info">todo</div></div></a></div><div class="next-post pull-right"><a href="/zwt-life/2023/10/24/gitee%20blog/" title="Gitee blog"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">Next</div><div class="next_info">Gitee blog</div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/zwt-life/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">John Doe</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/zwt-life/archives/"><div class="headline">Articles</div><div class="length-num">6</div></a><a href="/zwt-life/tags/"><div class="headline">Tags</div><div class="length-num">0</div></a><a href="/zwt-life/categories/"><div class="headline">Categories</div><div class="length-num">0</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>Announcement</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>Contents</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Zookeper"><span class="toc-number">1.</span> <span class="toc-text">Zookeper</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#0-%E6%98%AF%E4%BB%80%E4%B9%88"><span class="toc-number">1.1.</span> <span class="toc-text">0. 是什么</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#0-0-%E7%89%B9%E6%80%A7"><span class="toc-number">1.1.1.</span> <span class="toc-text">0.0 特性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#0-1-%E6%80%BB%E4%BD%93%E6%9E%B6%E6%9E%84"><span class="toc-number">1.1.2.</span> <span class="toc-text">0.1 总体架构</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#0-2-%E8%A7%92%E8%89%B2"><span class="toc-number">1.1.3.</span> <span class="toc-text">0.2 角色</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#0-3%E6%95%B0%E6%8D%AE%E6%A8%A1%E5%9E%8B"><span class="toc-number">1.1.4.</span> <span class="toc-text">0.3数据模型</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#0-4-%E5%9B%9B%E7%A7%8D%E8%8A%82%E7%82%B9"><span class="toc-number">1.1.5.</span> <span class="toc-text">0.4 四种节点</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E4%B8%BA%E4%BB%80%E4%B9%88%E8%A6%81%E4%BD%BF%E7%94%A8"><span class="toc-number">1.2.</span> <span class="toc-text">1. 为什么要使用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#ZooKeeper-%E8%AE%BE%E8%AE%A1%E7%9B%AE%E6%A0%87"><span class="toc-number">1.2.1.</span> <span class="toc-text">ZooKeeper 设计目标</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%9B%AE%E6%A0%87%E4%B8%80%EF%BC%9A%E9%AB%98%E6%80%A7%E8%83%BD%EF%BC%88%E7%AE%80%E5%8D%95%E7%9A%84%E6%95%B0%E6%8D%AE%E6%A8%A1%E5%9E%8B%EF%BC%89"><span class="toc-number">1.2.2.</span> <span class="toc-text">[目标一：高性能（简单的数据模型）]</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%9B%AE%E6%A0%87%E4%BA%8C%EF%BC%9A%E9%AB%98%E5%8F%AF%E7%94%A8%EF%BC%88%E6%9E%84%E5%BB%BA%E9%9B%86%E7%BE%A4%EF%BC%89"><span class="toc-number">1.2.3.</span> <span class="toc-text">[目标二：高可用（构建集群）]</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%9B%AE%E6%A0%87%E4%B8%89%EF%BC%9A%E9%A1%BA%E5%BA%8F%E4%B8%80%E8%87%B4%E6%80%A7%EF%BC%88%E4%BA%8B%E5%8A%A1%E6%93%8D%E4%BD%9C%E7%9A%84%E9%A1%BA%E5%BA%8F%EF%BC%89"><span class="toc-number">1.2.4.</span> <span class="toc-text">[目标三：顺序一致性（事务操作的顺序）]</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%9B%AE%E6%A0%87%E5%9B%9B%EF%BC%9A%E6%9C%80%E7%BB%88%E4%B8%80%E8%87%B4%E6%80%A7"><span class="toc-number">1.2.5.</span> <span class="toc-text">[目标四：最终一致性]</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="toc-number">1.3.</span> <span class="toc-text">2. 使用场景</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-%E5%91%BD%E5%90%8D%E6%9C%8D%E5%8A%A1%EF%BC%88Name-Service%EF%BC%89"><span class="toc-number">1.3.1.</span> <span class="toc-text">2.1 命名服务（Name Service）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-%E9%85%8D%E7%BD%AE%E4%B8%AD%E5%BF%83"><span class="toc-number">1.3.2.</span> <span class="toc-text">2.2 配置中心</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-3-%E9%9B%86%E7%BE%A4%E7%AE%A1%E7%90%86"><span class="toc-number">1.3.3.</span> <span class="toc-text">2.3 集群管理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-4-%E5%88%86%E5%B8%83%E5%BC%8F%E9%94%81"><span class="toc-number">1.3.4.</span> <span class="toc-text">2.4 分布式锁</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8"><span class="toc-number">1.4.</span> <span class="toc-text">3. 如何使用</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-java-%E5%AE%9E%E7%8E%B0"><span class="toc-number">1.4.1.</span> <span class="toc-text">3.1 java 实现</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%BB%BA%E7%AB%8B%E5%85%B3%E9%97%AD%E8%BF%9E%E6%8E%A5"><span class="toc-number">1.4.1.1.</span> <span class="toc-text">建立关闭连接</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E8%8A%82%E7%82%B9"><span class="toc-number">1.4.1.2.</span> <span class="toc-text">创建节点</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%9B%E5%BB%BA%E9%A1%BA%E5%BA%8F%E8%8A%82%E7%82%B9"><span class="toc-number">1.4.1.3.</span> <span class="toc-text">创建顺序节点</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%9B%B4%E6%96%B0%E8%8A%82%E7%82%B9"><span class="toc-number">1.4.1.4.</span> <span class="toc-text">更新节点</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%AE%BF%E9%97%AE%E8%8A%82%E7%82%B9"><span class="toc-number">1.4.1.5.</span> <span class="toc-text">访问节点</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%B7%BB%E5%8A%A0%E7%9B%91%E5%90%AC"><span class="toc-number">1.4.1.6.</span> <span class="toc-text">添加监听</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%A0%E9%99%A4%E8%8A%82%E7%82%B9"><span class="toc-number">1.4.1.7.</span> <span class="toc-text">删除节点</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-%E5%8E%9F%E7%90%86"><span class="toc-number">1.5.</span> <span class="toc-text">4. 原理</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-Session-%E4%BC%9A%E8%AF%9D"><span class="toc-number">1.5.1.</span> <span class="toc-text">4.1 Session 会话</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2-ZNode-%E8%8A%82%E7%82%B9"><span class="toc-number">1.5.2.</span> <span class="toc-text">4.2 ZNode 节点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-3-Watcher-%E7%9B%91%E5%90%AC%E5%99%A8"><span class="toc-number">1.5.3.</span> <span class="toc-text">4.3 Watcher 监听器</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-4-ACL-%E6%9D%83%E9%99%90%E6%8E%A7%E5%88%B6"><span class="toc-number">1.5.4.</span> <span class="toc-text">4.4 ACL 权限控制</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-5-ZAB-%E5%8E%9F%E5%AD%90%E5%B9%BF%E6%92%AD"><span class="toc-number">1.5.5.</span> <span class="toc-text">4.5 ZAB 原子广播</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#4-5-1-%E5%A5%94%E6%BA%83%E6%81%A2%E5%A4%8D"><span class="toc-number">1.5.5.1.</span> <span class="toc-text">4.5.1 奔溃恢复</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-5-2-%E5%B9%BF%E6%92%AD%E8%BF%87%E7%A8%8B"><span class="toc-number">1.5.5.2.</span> <span class="toc-text">4.5.2 广播过程</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%95%AA%E5%A4%96"><span class="toc-number">1.6.</span> <span class="toc-text">番外</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#zxid%EF%BC%8Cepoch"><span class="toc-number">1.6.1.</span> <span class="toc-text">zxid，epoch</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%82%E8%80%83"><span class="toc-number">1.7.</span> <span class="toc-text">参考</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>Recent Post</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/zwt-life/2023/10/25/todo/" title="todo">todo</a><time datetime="2023-10-25T07:14:45.519Z" title="Created 2023-10-25 15:14:45">2023-10-25</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/zwt-life/2023/10/25/Zookeper/" title="Zookeper">Zookeper</a><time datetime="2023-10-25T03:19:39.229Z" title="Created 2023-10-25 11:19:39">2023-10-25</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/zwt-life/2023/10/24/gitee%20blog/" title="Gitee blog">Gitee blog</a><time datetime="2023-10-24T03:25:27.640Z" title="Created 2023-10-24 11:25:27">2023-10-24</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/zwt-life/2023/10/24/hello-world/" title="Hello World">Hello World</a><time datetime="2023-10-24T03:09:38.044Z" title="Created 2023-10-24 11:09:38">2023-10-24</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/zwt-life/2023/10/23/%E7%BC%93%E5%AD%98%E7%9A%84%E5%A5%A5%E4%B9%89/" title="缓存">缓存</a><time datetime="2023-10-23T13:04:48.005Z" title="Created 2023-10-23 21:04:48">2023-10-23</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By John Doe</div><div class="framework-info"><span>Framework </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>Theme </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="Toggle Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between Single-column and Double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="Back To Top"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/zwt-life/js/utils.js"></script><script src="/zwt-life/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>